#include <node_api.h>
#include "utils.h"

// 加法函数
napi_value Add(napi_env env, napi_callback_info info) {
    double a = GetNumberFromArgs(env, info, 0);
    double b = GetNumberFromArgs(env, info, 1);
    return CreateNumber(env, a + b);
}

// 减法函数
napi_value Subtract(napi_env env, napi_callback_info info) {
    double a = GetNumberFromArgs(env, info, 0);
    double b = GetNumberFromArgs(env, info, 1);
    return CreateNumber(env, a - b);
}

// 乘法函数
napi_value Multiply(napi_env env, napi_callback_info info) {
    double a = GetNumberFromArgs(env, info, 0);
    double b = GetNumberFromArgs(env, info, 1);
    return CreateNumber(env, a * b);
}

// 除法函数
napi_value Divide(napi_env env, napi_callback_info info) {
    double a = GetNumberFromArgs(env, info, 0);
    double b = GetNumberFromArgs(env, info, 1);
    
    if (b == 0) {
        ThrowError(env, "Division by zero");
        return CreateUndefined(env);
    }
    
    return CreateNumber(env, a / b);
}

// 创建计算器对象
napi_value CreateCalculator(napi_env env, napi_callback_info info) {
    // 创建一个空对象
    napi_value calculator = CreateObject(env);
    
    // 设置PI常量
    SetProperty(env, calculator, "PI", CreateNumber(env, 3.141592653589793));
    
    // 添加方法
    SetProperty(env, calculator, "add", CreateFunction(env, "add", Add));
    SetProperty(env, calculator, "subtract", CreateFunction(env, "subtract", Subtract));
    SetProperty(env, calculator, "multiply", CreateFunction(env, "multiply", Multiply));
    SetProperty(env, calculator, "divide", CreateFunction(env, "divide", Divide));
    
    // 添加实例属性
    SetProperty(env, calculator, "value", CreateNumber(env, 0.0));
    SetProperty(env, calculator, "name", CreateString(env, "Calculator"));
    
    return calculator;
}

// 模块初始化函数
napi_value Init(napi_env env, napi_value exports) {
    // 定义要导出的方法
    napi_property_descriptor desc[] = {
        { "add", NULL, Add, NULL, NULL, NULL, napi_default, NULL },
        { "subtract", NULL, Subtract, NULL, NULL, NULL, napi_default, NULL },
        { "multiply", NULL, Multiply, NULL, NULL, NULL, napi_default, NULL },
        { "divide", NULL, Divide, NULL, NULL, NULL, napi_default, NULL },
        { "Calculator", NULL, CreateCalculator, NULL, NULL, NULL, napi_default, NULL }
    };
    
    // 导出所有方法
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    
    // 导出常量
    SetProperty(env, exports, "VERSION", CreateString(env, "1.0.0"));
    SetProperty(env, exports, "AUTHOR", CreateString(env, "Node-API Toolkit"));
    
    return exports;
}

// 注册模块
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)